﻿using Nacos.V2;

namespace Service.Core.OpenFegin
{
    public class NacosServiceDiscoveryService(INacosNamingService nacosNamingService) : IServiceDiscoveryService
    {
        public async Task<Uri> GetInstancesAsync(string serviceName)
        {
            if (nacosNamingService == null)
            {
                throw new ArgumentNullException(nameof(nacosNamingService), "Nacos naming service cannot be null.");
            }
            var instance = await nacosNamingService.SelectOneHealthyInstance(serviceName);
            if (instance == null)
            {
                throw new InvalidOperationException($"Nacos No healthy instance found for service: {serviceName}");
            }
            return new UriBuilder()
            {
                Scheme = "http",
                Host = instance.Ip,
                Port = instance.Port
            }.Uri;
        }
    }
}
